<template>
    <h4>选择商品【{{ props.goodsName}}】的序列号</h4>
    <!-- 分割线 -->
    <el-divider style="margin: 10px 0" />
    <div style="padding:20px">
        <!-- 表格 -->
        <el-table :data="serialList" style="width: 100%" border>
            <!-- 操作列 -->
            <el-table-column label="操作" width="80px" align="center" fixed="left" v-if="Number(props.status) < 2">
                <template #default="scope">
                    <!-- add -->
                    <el-button link type="success" size="small" plain @click="addDetailRow(scope.$index)"><el-icon>
                            <Plus />
                        </el-icon></el-button>
                    <!-- del -->
                    <el-button link type="danger" size="small" plain @click="removeDetailRow(scope.$index)"><el-icon>
                            <Minus />
                        </el-icon></el-button>
                </template>
            </el-table-column>

            <!-- 序列号 -->
            {{ props.status }}
            <el-table-column label="序列号" width="180" align="center">
                <template #default="scope">
                    <el-input v-model="scope.row.serialNo" style="width: 95%" placeholder="输入序列号" :readonly="Number(props.status) >= 2"/>
                </template>
            </el-table-column>

            <!-- 备注 -->
            <el-table-column prop="warehouseLocationCode" label="备注" width="180" align="center">
                <template #default="scope">
                    <el-input style="width: 95%" v-model="scope.row.remark" :readonly="Number(props.status) >= 2"/>
                </template>
            </el-table-column>
        </el-table><br />
    </div>

</template>



<script setup>
import { defineProps, ref, defineExpose, watch} from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps(["goodsName", "list", "status"])

let serialList = ref([{
    serialNo: '',
    remark: '',
}])

// 监听 props.list 的变化，并同步到本地 serialList，不能使用onMounted，因为第一次点击时后续就不会改变了
watch(
  () => props.list,
  (newList) => {
    // 深拷贝，避免直接引用导致双向绑定污染父组件
    serialList.value = (newList || []).map(item => ({
      serialNo: item.serialNo || '',
      remark: item.remark || ''
    }));
    // 如果列表为空，初始化一行
    if (serialList.value.length === 0) {
      serialList.value.push({ serialNo: '', remark: '' });
    }
  },
  { immediate: true } // 立即执行一次
);


const addDetailRow = (index) => {
  serialList.value.splice(index + 1, 0, {});
}
const removeDetailRow = (index) => {
  if (serialList.value.length === 1) {
    ElMessage({
      message: '至少保留一条记录',
      type: 'warning',
    })
    return;
  }
  serialList.value.splice(index, 1);
}

const getValidSerialList = () => {
  return serialList.value.filter(item => item.serialNo?.trim());
};

defineExpose({
  getValidSerialList,
});

</script>

<style></style>